<template>
  <a-drawer
    :title="title"
    :width="720"
    :visible="visible"
    :wrapStyle="{height: '100%',overflow: 'auto',paddingBottom: '108px'}"
    @close="close"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="标题"
        >
          <a-input placeholder="请输入案例标题" v-decorator="[ 'title', {rules: [{ required: true, message: '请输入案例标题!' }]}]"/>
        </a-form-item>

        <a-form-item
          label="分类"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <tree-select
            style="width:100%"
            :dropdownStyle="{ maxHeight: '200px', overflow: 'auto' }"
            :treeData="treeData"
            v-decorator="['varietyId', {rules: [{ required: true, message: '请选择案例分类!' }]}]"
            placeholder="请选择案例的分类"
          >
          </tree-select>
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="描述"
        >
          <a-input placeholder="请输入案例描述" v-decorator="[ 'description', {rules: [{ required: true, message: '请输入案例描述!' }]}]"/>
        </a-form-item>

        <a-form-item label="封面" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-upload
            v-decorator="[
              'fileField',
              {
                valuePropName: 'fileList',
                getValueFromEvent: normFile,
                initialValue: [],
                preserve: true,
                rules: [{ required: true, message: '请选择封面图片!' }]
              },
            ]"
            listType="picture-card"
            :beforeUpload="handleBeforeUploadPhoto"
            :customRequest="uploadPhoto"
            :remove="() => {this.showUpload = true}"
            @preview="handlePreviewPhoto"
          >
            <div v-if="showUpload">
              <a-icon type="plus" />
              <div class="ant-upload-text">点击上传</div>
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item hidden>
          <a-input v-decorator="[ 'coverFileId' ]"/>
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="视频详情"
        >
          <a-input placeholder="请输入视频详情" v-decorator="[ 'detail', {rules: [{ required: true, message: '请输入视频详情!' }]}]"/>
        </a-form-item>

        <a-form-item label="视频" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-upload
            v-decorator="[
              'videoFileField',
              {
                valuePropName: 'fileList',
                getValueFromEvent: normFile,
                initialValue: [],
                preserve: true,
                rules: [{ required: true, message: '请上传视频文件!' }]
              },
            ]"
            :beforeUpload="handleBeforeUploadVideo"
            :customRequest="uploadVideo"
            :remove="removePhoto"
          >
            <a-button v-if="showUploadVideo"> <a-icon type="upload" /> 点击上传 </a-button>
          </a-upload>
        </a-form-item>
        <a-form-item hidden>
          <a-input v-decorator="[ 'videoFileId' ]"/>
        </a-form-item>

      </a-form>
    </a-spin>

    <div style="padding: 20px 40px 60px 40px" v-if="showComment">
      <a-divider v-if="commentToggle"><a @click="openComment">点击展开评论<a-icon style="margin-left: 8px" type="down" /></a></a-divider>
      <a-divider v-else><a @click="commentToggle = true">点击收起评论<a-icon style="margin-left: 8px" type="up" /></a></a-divider>
      <a-list item-layout="vertical" v-if="!commentToggle">
        <a-list-item v-for="count in 10" :key="count">
          <div class="content">
            <a-tag color="#2db7f5">正常</a-tag>
            好棒哦好棒哦好棒哦好棒哦好棒哦好棒哦好棒哦好棒哦好棒哦好棒哦好棒哦好棒哦好棒哦好棒哦好棒哦好棒哦好棒哦好棒哦好棒哦好棒哦好棒哦好棒哦好棒哦好棒哦好棒哦
          </div>
          <div class="customer-info">
            张三
            <em>2018-08-05 22:23</em>
          </div>
          <span slot="actions"><a-icon style="margin-right: 8px" type="eye-invisible" />隐藏</span>
          <span slot="actions"><a-icon style="margin-right: 8px" type="delete" />删除</span>
        </a-list-item>
      </a-list>
    </div>

    <div class="drawer-bottom-button">
      <a-button :style="{marginRight: '8px'}" @click="close">取消</a-button>
      <a-button @click="handleSubmit" type="primary" :loading="confirmLoading">保存</a-button>
    </div>
  </a-drawer>
</template>

<script>
import { TreeSelect } from 'ant-design-vue'
import { FormModalMixin } from '@/mixins/FormModalMixin'
import { apiQueryCaseInfoById, apiQueryArticleVarietyTree, apiSaveCaseInfo, apiUpdateCaseInfo } from '@/api/article'
import pick from 'lodash.pick'
import { apiUploadFile } from '@/api/file'
import { CASE_INFO_STATUS_ENUM } from '@/store/mutation-types'

export default {
  name: 'CaseInfoModal',
  components: {
    TreeSelect
  },
  mixins: [FormModalMixin],
  data () {
    return {
      treeData: [],
      previewVisible: false,
      previewImage: '',
      showUpload: true,
      showUploadVideo: true,
      uploadVideo: null,
      commentToggle: true,
      showComment: false,
      caseInfoStatusEnum: CASE_INFO_STATUS_ENUM
    }
  },
  created () {
    this.uploadVideo = (option) => {
      const formData = new FormData()
      formData.append('multipartFile', option.file)
      this.showUploadVideo = false
      apiUploadFile(formData, (e) => {
        console.log('apiUploadFile=', e)
        let percent = (e.loaded / e.total) * 100
        if (percent > 99) {
          percent = 99
        }
        option.onProgress({ percent: percent })
      }).then(res => {
        option.onProgress({ percent: 100 })
        console.log('onSuccess')
        this.form.setFieldsValue({
          videoFileId: res.data.id
        })
        option.onSuccess()
      }).catch(err => {
        option.onError(err, err.message)
      })
    }
  },
  methods: {
    show (title, record) {
      this.resetFields()
      this.model = {}
      this.showUpload = true
      this.showUploadVideo = true
      this.visible = true
      this.title = title
      this.loadVarietyTree()
      if (record) {
        apiQueryCaseInfoById(record.id).then(res => {
          this.model = Object.assign({}, res.data)
          this.$nextTick(() => {
            this.form.setFieldsValue(pick(this.model, 'id', 'title', 'varietyId', 'summary', 'status', 'detail'))
          })
        })
      }
    },
    loadVarietyTree () {
      const that = this
      apiQueryArticleVarietyTree().then(res => {
        that.treeData = that.getTreeData(res.data)
      })
    },
    getTreeData (list) {
      const treeData = []
      for (let i = 0; i < list.length; i++) {
        const temp = {
          title: list[i].name,
          value: list[i].id,
          key: list[i].id
        }
        if (list[i].children !== null && list[i].children.length > 0) {
          temp.children = [...this.getTreeData(list[i].children)]
        }
        treeData.push(temp)
      }
      return treeData
    },
    normFile (e) {
      console.log('Upload event:', e)
      if (Array.isArray(e)) {
        return e
      }
      return e && e.fileList
    },
    handleBeforeUploadPhoto (file, fileList) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      return new Promise((resolve, reject) => {
        if (!isJPG) {
          this.$message.error('请选择jpg或png文件！')
          reject(file)
        } else if (fileList.length > 1) {
          this.$message.error('最多上传1个文件！')
        } else {
          resolve(file)
        }
      })
    },
    uploadPhoto (e) {
      this.showUpload = false
      const formData = new FormData()
      formData.append('multipartFile', e.file)
      apiUploadFile(formData).then(res => {
        console.log('uploadPhoto=>', res)
        this.form.setFieldsValue({
          coverFileId: res.data.id
        })
        e.onSuccess()
      }).catch(err => {
        e.onError(err, err.message)
      })
    },
    removePhoto () {
      this.showUpload = true
      this.form.setFieldsValue({
        fileField: [],
        coverFileId: null
      })
    },
    handlePreviewPhoto (file) {
      console.log(file)
      this.previewImage = file.url || file.thumbUrl
      this.previewVisible = true
    },
    handleBeforeUploadVideo (file, fileList) {
      console.log('上传的文件==>', file)
      const videoTypes = ['video/mp4', 'video/x-ms-asf', 'video/avi', 'video/x-ivf', 'video/x-mpeg', 'video/mpeg4', 'video/x-sgi-movie', 'video/x-mpg', 'video/mpg', 'video/x-ms-wmv', 'video/x-ms-wm', 'video/x-ms-wmx', 'video/x-ms-wvx']
      const flag = videoTypes.indexOf(file.type) >= 0
      return new Promise((resolve, reject) => {
        if (!flag) {
          this.$message.error('不支持的视频文件！')
          reject(file)
        } else if (fileList.length > 1) {
          this.$message.error('最多上传1个文件！')
        } else {
          resolve(file)
        }
      })
    },
    openComment () {
      this.commentToggle = false
    },
    handleSubmit () {
      this.form.validateFields((err, values) => {
        if (!err) {
          this.confirmLoading = false
          const formData = pick(Object.assign(this.model, values), 'title', 'varietyId', 'description', 'coverFileId', 'videoFileId', 'detail')
          let obj
          if (this.model.id) {
            obj = apiUpdateCaseInfo(this.model.id, formData)
          } else {
            formData.status = this.caseInfoStatusEnum.INIT.KEY
            obj = apiSaveCaseInfo(formData)
          }
          obj.then(res => {
            if (res.code === 1) {
              this.$message.success(res.msg)
              this.$emit('ok', res.data)
              this.close()
            } else {
              this.$message.warning(res.msg)
            }
          }).finally(() => {
            this.confirmLoading = false
          })
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.content {
  line-height: 25px;
}
.customer-info {
  margin-top: 16px;
  em {
    color: @disabled-color;
    font-style: normal;
    margin-left: 16px;
  }
}

</style>
